package com.topcent.tioxyc.xxljob;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.PurchaseOrderListMapper;
import com.topcent.tioxyc.mapper.SalesGrossProfitDataMapper;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.Assignee;
import com.topcent.tioxyc.pojo.PurchaseOrderList;
import com.topcent.tioxyc.pojo.SalesGrossProfitData;
import com.topcent.tioxyc.pojo.ZPurchaseOrderList;
import com.topcent.tioxyc.pojo.vo.Wuliao01VO;
import com.topcent.tioxyc.service.PurchaseOrderListService;
import com.topcent.tioxyc.service.SalesGrossProfitDataService;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/3/31 11:12
 * @Description: 销售毛利数据 AND 采购订单列表（含收货）API
 */
@Slf4j
@Component
public class SalesGrossProfitDataXxlJob {
    @Autowired
    private SalesGrossProfitDataService salesGrossProfitDataService;
    @Autowired
    private SalesGrossProfitDataMapper salesGrossProfitDataMapper;
    @Autowired
    private PurchaseOrderListService purchaseOrderListService;
    @Autowired
    private PurchaseOrderListMapper purchaseOrderListMapper;
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @XxlJob("salesGrossProfitData")
    public void salesGrossProfitData(){
        Header[] headers = new Header[3];
        String auth = KeyConstant.sapSALE001APIName + ":" + KeyConstant.sapSALE001APIPass;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        headers[0] = new BasicHeader("Accept", "application/json");
        headers[1] = new BasicHeader("Authorization", authHeader);
        headers[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries =
                ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_SALE001API_CDS/YY1_SALE001API", headers, null);
        String d = entries.getStr("d");
        JSONObject objects = JSONUtil.parseObj(d);
        String results = objects.getStr("results");
        JSONArray objectss = JSONUtil.parseArray(results);
        List<SalesGrossProfitData> salesGrossProfitDataList = JSONUtil.toList(objectss, SalesGrossProfitData.class);
        salesGrossProfitDataMapper.truncateTable();
        boolean success = salesGrossProfitDataService.saveBatch(salesGrossProfitDataList);


        JSONObject entries1 = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_YY1_PO3API_CDS/YY1_YY1_PO3API", headers, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<PurchaseOrderList> purchaseOrderList = JSONUtil.toList(objectss1, PurchaseOrderList.class);
        // 物料集合
        List<Wuliao01VO> wuliao01VOList = selectList();
        // 1. 将 wuliao01VOList 先转换为 Map，以 b 字段为 key，c 字段为 value，提高查找效率
        Map<String, String> bToCMap = wuliao01VOList.stream()
                .collect(Collectors.toMap(Wuliao01VO::get_widget_1720490004612, Wuliao01VO::get_widget_1720490004647, (v1, v2) -> v1)); // key重复取第一个

        // 合并 PurchaseOrder 和 PurchaseOrderType 相同的记录（DeliveredQuantity、DeliveredAmount 累加）
        Map<String, PurchaseOrderList> mergedMap = new HashMap<>();
        for (PurchaseOrderList item : purchaseOrderList) {
            if (StrUtil.isBlank(item.getPurchaseOrder()) || StrUtil.isBlank(item.getPurchaseOrderItem())) {
                continue;
            }
            String key = item.getPurchaseOrder() + "-" + item.getPurchaseOrderItem(); // 组合成唯一key
            if (mergedMap.containsKey(key)) {
                PurchaseOrderList existing = mergedMap.get(key);
                // 累加数量
                if (item.getDeliveredQuantity() != null) {
                    existing.setDeliveredQuantity(
                            (existing.getDeliveredQuantity() == null ? 0 : existing.getDeliveredQuantity())
                                    + item.getDeliveredQuantity()
                    );
                }
                // 累加金额
                if (item.getDeliveredAmount() != null) {
                    existing.setDeliveredAmount(
                            (existing.getDeliveredAmount() == null ? BigDecimal.ZERO : existing.getDeliveredAmount())
                                    .add(item.getDeliveredAmount())
                    );
                }
            } else {
                mergedMap.put(key, item);
            }
        }
        List<PurchaseOrderList> mergedList = new ArrayList<>(mergedMap.values());
        for (PurchaseOrderList yy1Kpi : mergedList){
            String key = yy1Kpi.getMaterial();  // 获取 A 字段（比如物料号）
            if (StrUtil.isNotBlank(key) && bToCMap.containsKey(key)) {
                yy1Kpi.setValuationClass(bToCMap.get(key));  // 设置 D 字段
            }
            if (yy1Kpi.getPurchaseOrderDate() != null && !yy1Kpi.getPurchaseOrderDate().isBlank()) {
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(yy1Kpi.getPurchaseOrderDate()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                yy1Kpi.setPurchaseOrderDate(dateTime4.toString());
            }
            if (yy1Kpi.getScheduleLineDeliveryDate() != null && !yy1Kpi.getScheduleLineDeliveryDate().isBlank()) {
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(yy1Kpi.getScheduleLineDeliveryDate()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);
                yy1Kpi.setScheduleLineDeliveryDate(dateTime4.toString());
            }
        }
        purchaseOrderListMapper.truncateTable();
        boolean success1 = purchaseOrderListService.saveBatch(mergedList);

        log.info(success ? "成功插入销售毛利数据：" + salesGrossProfitDataList.size() + " 条" : "数据插入失败");
        log.info(success1 ? "成功插入采购订单列表（含收货）API数据：" + mergedList.size() + " 条" : "数据插入失败");

        // 采购单数据-简道云
        purchaseOrderYunData();
    }

    public List<Wuliao01VO> selectList(){
        Header[] headers = ConnmeUtils.createHeaders();
        // 获取到产品主数据数据。
        List<Wuliao01VO> consolidatedOrderVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "668c9750508d1d2bf336211a");
        parameter.put("entry_id", "668c98146b86173be43e6a21");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Wuliao01VO> list = JSONUtil.toList(objects, Wuliao01VO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            consolidatedOrderVOList.addAll(list);
        } while (fale);
        log.info("产品主数据表单数据size：" + consolidatedOrderVOList.size());
        return consolidatedOrderVOList;
    }

    public String purchaseOrderYunData() {
        String appId = "67f8aa2676b9b3942c49035f";
        String entryId = "67ff675568c6ea7be7efebe9";
        Header[] headers = ConnmeUtils.createHeaders();
        //批量删除简道云数据
        ConnmeUtils.selectAndDeleteList(headers, appId, entryId, "");
        // 获取原始数据
        List<PurchaseOrderList> originalData = yy1KpiMapper.selectPurchaseOrderAll();

        // 获取用户人员信息
        Map<String ,Object> person =new HashMap<>();
        person.put("dept_no", 1);
        person.put("has_child", true);
        JSONObject personResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/user/list", headers, JSONUtil.toJsonStr(person));
        String personData = personResult.getStr("users");
        JSONArray personObjects = JSONUtil.parseArray(personData);
        List<Assignee> personList = JSONUtil.toList(personObjects, Assignee.class);

        Map<String, String> userNameMap = personList.stream()
                .collect(Collectors.toMap(Assignee::getName, Assignee::getUsername, (v1, v2) -> v1));
        // 按供应商分组
        Map<String, List<PurchaseOrderList>> groupedBySupplier = originalData.stream()
                .collect(Collectors.groupingBy(PurchaseOrderList::getSupplier));

        // 遍历每组
        for (Map.Entry<String, List<PurchaseOrderList>> entry : groupedBySupplier.entrySet()) {
            List<PurchaseOrderList> list = entry.getValue();

            // 找出该组中最晚的订单时间
            Optional<String> latestDateOpt = list.stream()
                    .map(PurchaseOrderList::getPurchaseOrderDate)
                    .filter(Objects::nonNull)
                    .max(String::compareTo);

            if (latestDateOpt.isPresent()) {
                String latestDate = latestDateOpt.get();
                // 给每条记录设置相同的最新时间
                list.forEach(po -> po.setRecentTime(latestDate));
            }
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 将处理后的数据存入简道云
        for (PurchaseOrderList entity : originalData) {
            if (entity.getDeliveredQuantity() != null && entity.getDeliveredQuantity() < 0) {
                if (entity.getConditionAmount_1() != null && entity.getConditionAmount_1().compareTo(BigDecimal.ZERO) > 0) {
                    entity.setConditionAmount_1(entity.getConditionAmount_1().negate());
                }

                if (entity.getOrderQuantity() != null && !entity.getOrderQuantity().startsWith("-")) {
                    entity.setOrderQuantity("-" + entity.getOrderQuantity());
                }
                if (entity.getOrderQuantity1() != null && !entity.getOrderQuantity1().startsWith("-")) {
                    entity.setOrderQuantity1("-" + entity.getOrderQuantity1());
                }

                if (entity.getNetAmount() != null && !entity.getNetAmount().startsWith("-")) {
                    entity.setNetAmount("-" + entity.getNetAmount());
                }
                if (entity.getNetAmount1() != null && !entity.getNetAmount1().startsWith("-")) {
                    entity.setNetAmount1("-" + entity.getNetAmount1());
                }
                if (entity.getConditionAmount() != null && !entity.getConditionAmount().startsWith("-")) {
                    entity.setConditionAmount("-" + entity.getConditionAmount());
                }

                if (entity.getNetPriceAmount() != null && !entity.getNetPriceAmount().startsWith("-")) {
                    entity.setNetPriceAmount("-" + entity.getNetPriceAmount());
                }
                if (entity.getNetPriceAmount1() != null && !entity.getNetPriceAmount1().startsWith("-")) {
                    entity.setNetPriceAmount1("-" + entity.getNetPriceAmount1());
                }
                if (entity.getConditionRateValue() != null && !entity.getConditionRateValue().startsWith("-")) {
                    entity.setConditionRateValue("-" + entity.getConditionRateValue());
                }
                if (entity.getConditionRateValue1() != null && !entity.getConditionRateValue1().startsWith("-")) {
                    entity.setConditionRateValue1("-" + entity.getConditionRateValue1());
                }
            }

            ZPurchaseOrderList vo = new ZPurchaseOrderList();
            vo.set_widget_1744791381513(entity.getPurchaseOrder());vo.set_widget_1744791381514(entity.getPurchaseOrderItem());vo.set_widget_1744791381515(entity.getPurchaseOrderType());vo.set_widget_1744791381516(entity.getPurchasingDocumentTypeName());
            vo.set_widget_1744791381517(entity.getSupplier());vo.set_widget_1744791381518(entity.getSupplierName());vo.set_widget_1744791381519(entity.getPurchaseOrderDate());vo.set_widget_1744791381520(entity.getPaymentTerms());
            vo.set_widget_1744791381521(entity.getPaymentTermsName());vo.set_widget_1744791381522(entity.getPurchaseOrderItemCategory());vo.set_widget_1744791381523(entity.getPurgDocItemCategoryName());
            vo.set_widget_1744791381524(entity.getAccountAssignmentCategory());vo.set_widget_1744791381525(entity.getAcctAssignmentCategoryName());
            vo.set_widget_1744791381526(entity.getMaterial());vo.set_widget_1744791381527(entity.getPurchaseOrderItemText());
            String quantityStr = entity.getOrderQuantity();
            vo.set_widget_1744941776389(
                    (quantityStr == null || quantityStr.trim().isEmpty()) ? null : Integer.valueOf(quantityStr)
            );
            String quantityStr1 = entity.getOrderQuantity1();
            vo.set_widget_1744941776388(
                    (quantityStr1 == null || quantityStr1.trim().isEmpty()) ? null : Integer.valueOf(quantityStr1)
            );
            vo.set_widget_1744791381530(entity.getPurchaseOrderQuantityUnit());
            vo.set_widget_1744791381531(entity.getUnitOfMeasureLongName());vo.set_widget_1744791381532(entity.getNetPriceAmount());
            vo.set_widget_1744791381533(entity.getNetPriceAmount1());vo.set_widget_1744791381534(entity.getConditionRateValue());
            vo.set_widget_1744791381535(entity.getConditionRateValue1());vo.set_widget_1744791381536(entity.getConditionCurrency());vo.set_widget_1744791381537(entity.getNetAmount());vo.set_widget_1744791381538(entity.getNetAmount1());
            vo.set_widget_1744791381539(entity.getConditionAmount());vo.set_widget_1744791381540(entity.getDocumentCurrency());vo.set_widget_1744791381541(entity.getConditionQuantity());
            vo.set_widget_1744791381542(entity.getConditionQuantityUnit());vo.set_widget_1744791381543(entity.getTax());vo.set_widget_1744791381544(entity.getMaterialGroup());vo.set_widget_1744791381545(entity.getMaterialGroupName());
            vo.set_widget_1744791381546(entity.getPlant());vo.set_widget_1744791381547(entity.getPlantName());
            vo.set_widget_1744791381548(entity.getStorageLocation());vo.set_widget_1744791381549(entity.getStorageLocationName());
            vo.set_widget_1744791381550(entity.getScheduleLineDeliveryDate());vo.set_widget_1744791381551(entity.getIsReturnsItem());vo.set_widget_1744791381552(entity.getPurchaseRequisition());vo.set_widget_1744791381553(entity.getPurchaseRequisitionItem());vo.set_widget_1744791381554(entity.getSalesOrder());vo.set_widget_1744791381555(entity.getSalesOrderItem());
            vo.set_widget_1744791381556(entity.getYY1_ZBMCL_PO_PDI());vo.set_widget_1744791381557(entity.getYY1_ZCPJZ_PO_PDI());vo.set_widget_1744791381558(entity.getYY1_ZPJ_PO_PDI());
            vo.set_widget_1744791381559(entity.getYY1_ZBZXX_PO_PDI());vo.set_widget_1744791381560(entity.getYY1_ZCL_PO_PDI());
            vo.set_widget_1744791381561(entity.getYY1_KS_PO_PDI());vo.set_widget_1744791381562(entity.getYY1_ZGGCC_PO_PDI());
            vo.set_widget_1744791381563(entity.getVCDescription());vo.set_widget_1744877640041(entity.getPurchasingGroupName());
            vo.set_widget_1744791381565(entity.getAddressSearchTerm1());vo.set_widget_1744791381566(entity.getSupplierRespSalesPersonName());
            vo.set_widget_1744791381567(entity.getAuthorizationGroupText());vo.set_widget_1744791381568(entity.getBusinessPartnerName1());
            vo.set_widget_1744791381569(entity.getPersonFullName());vo.set_widget_1744791381570(entity.getPurchasingDocumentDeletionCode());
            vo.set_widget_1744791381571(entity.getIsCompletelyDelivered());vo.set_widget_1744791381572(entity.getCurrency());
            vo.set_widget_1744791381573(entity.getExchangeRate());vo.set_widget_1744791381574(entity.getUnitOfMeasure());
            vo.set_widget_1744791381575(entity.getPurchasingProcessingStatus());vo.set_widget_1744791381576(entity.getDivision());
            vo.set_widget_1744791381577(entity.getPersonFullName_1());vo.set_widget_1744791381578(entity.getTaxCode());
            vo.set_widget_1744791381579(entity.getExchangeRate_1());vo.set_widget_1744791381580(entity.getSalesOffice());vo.set_widget_1744791381581(entity.getGlobalCurrency());vo.set_widget_1744791381582(entity.getSalesOrganization());vo.set_widget_1744795545795(entity.getRecentTime());vo.set_widget_1744877326805(entity.getProductType());vo.set_widget_1744941776391(entity.getProductTypeName());
            vo.set_widget_1744946520199(entity.getDeliveredQuantity());vo.set_widget_1744946520200(entity.getConditionAmount_1());vo.set_widget_1745202497032(entity.getDeliveredAmount());vo.set_widget_1745223232087(entity.getValuationClass());

            String username = userNameMap.get(vo.get_widget_1744877640041());
            if (username != null) {
                vo.set_widget_1744877640041(username);
            }
            vo.set_id(null);
            mapList.add(ConnmeUtils.convertEntityToMap(vo));
        }
        //批量新增到简道云
        ConnmeUtils.batchAddList(headers, appId, entryId, mapList);
        return "success数量：" + mapList.size();
    }
}
